<?php

namespace Pm\Controllers;

use Admin\Models\pm\XhwoWorkOrder;
use Admin\Models\pm\XhwoWorkOrderMember;
use Admin\Models\pm\XhwoWorkOrderLog;
use Admin\Models\user\XhsysUser;
use Admin\Models\bpm\XHBpmTemplate;
use Admin\Models\bpm\XHBpmNode;
use Helpers\Main;
use Helpers\Assets;
use Modules\Power;
use Helpers\User;
use Helpers\Tool;

class WorkorderController extends ControllerBase
{
    private static $workorder_levels = [
        1 => '普通',
        2 => '重要',
        3 => '紧急',
    ];

    private static $workorder_status = [
        1 => '待处理',
        2 => '进行中',
        3 => '已完成',
        4 => '已退回',
    ];

    /**
     * 工单列表
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180515
     */
    public function indexAction()
    {
        if (!Power::exist('Pm_Work_Order')) {
            return $this->sendViewError('无工单权限');
        }
        $this->di->get('assets')
            ->addCss('assets/sweetalert2/sweetalert2.min.css')
            ->addJs('assets/sweetalert2/sweetalert2.min.js');
        Main::showNavPosition();
        Assets::easyUI();
        Assets::importJs('js/myMain.js');
        $this->view->pick('workorder/workOrderList');
        Assets::importJs('js/workorder/workOrderList.js');
        Assets::importMainJs('assets/xh/xhForm.js');
        Assets::importMainJs('assets/xh/xhTop.js');
        $this->view->setVars([
            'workOrderStatus' => self::$workorder_status,
            'workOrderLevels' => self::$workorder_levels,
            'workOrderEdit' => Power::exist('Pm_Work_Order_Edit'),
            'workOrderDel' => Power::exist('Pm_Work_Order_Del'),
            'workOrderAdd' => Power::exist('Pm_Work_Order_Add'),
            'workOrderCheck' => Power::exist('Pm_Work_Order_Check'),
            'workOrderAlter' => Power::exist('Pm_Work_Order_AlterStatus'),
        ]);
    }

    /**
     * 获取工单列表
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180515
     */
    public function getWorkOrderAction()
    {
        try {
            if (!Power::exist('Pm_Work_Order')) {
                return $this->sendErrorResponse(500, '权限不足', '无工单权限');
            }
            $status = $this->request->getPost('status', 'int'); //根据状态筛选
            $level = $this->request->getPost('level', 'int'); //根据等级筛选
            $sWorkOrderName = $this->request->getPost('sWorkOrderName', 'string'); //根据用户id
            $condition = "w.bDelete = 0 AND w.iParentId = 0";
            $condition .= $status ? " AND w.iWorkOrderStatus = $status " : "";
            $condition .= $level ? " AND w.iLevel = $level " : '';
            $condition .= $sWorkOrderName ? " AND (w.sWorkOrderName LIKE '%$sWorkOrderName%' OR w.sWorkOrderContent LIKE '%$sWorkOrderName%' )" : '';
            $wids = $this->getWorkOrderIds(); //获取能查看的列表
            if (!$wids && !User::isAdmin()) {
                return $this->sendJsonResponse([]);
            }
            $condition1 = "bDelete=0 AND iParentId = :iParentId: ";
            $builder = $this->modelsManager->createBuilder()
                ->columns("u.sStaffName,w.iWorkOrderId,w.iParentId,w.sWorkOrderName,w.dWorkTime,
                w.sWorkOrderContent,w.iLevel,w.iWorkOrderStatus,w.iProcess,w.sRemarks,w.sExplain,w.sComments,
                w.bIfChecked,w.tFromAt,w.tEndAt,w.tStartedAt,w.tFinishedAt,w.tCreateDate,
                w.tLastModifyDate,w.sEnclosure")
                ->addFrom('Admin\Models\pm\XhwoWorkOrder', 'w')
                ->leftjoin('Admin\Models\pm\XhwoWorkOrderMember', 'm.iWorkOrderId=w.iWorkOrderId AND m.bIfExecutor =1 AND m.bDelete = 0', 'm')
                ->leftjoin('Admin\Models\hrm\XhhrmStaff', 'm.iUserId = u.iUserId', 'u')
                ->where($condition);
                if (!User::isAdmin()) {
                    $builder->inwhere('w.iWorkOrderId', $wids);
                }
            $builder->orderBy("w.iWorkOrderId desc");
            $data = Main::runBuilderPages($builder, true);
            foreach ($data['rows'] as $key => $value) {
                $objs = $this->modelsManager->createBuilder()
                    ->columns('iWorkOrderId')
                    ->addFrom('Admin\Models\pm\XhwoWorkOrder')
                    ->where($condition1, ['iParentId' => $value['iWorkOrderId']])
                    ->inWhere('iWorkOrderId', $wids)
                    ->getQuery()
                    ->execute()
                    ->toArray();
                $data['rows'][$key]['state'] = empty($objs) ? '' : "closed";
                $data['rows'][$key]['iconCls'] = empty($objs) ? 'fa fa-file-text' : 'fa fa-folder';
                $children = $this->getWorkOrderChildren($value['iWorkOrderId'], $wids);
                $data['rows'][$key]['children'] = $children;
            }
            return $this->sendJsonResponse($data);
        } catch (\Exception $exception) {
            return $this->sendErrorResponse(500, '获取失败！', $exception->getMessage());
        }
    }

    /**
     * 获取children
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180523
     */
    private function getWorkOrderChildren($wid, $wids)
    {
        $condition = "w.bDelete=0 AND w.iParentId=:iParentId:";
        $condition1 = "bDelete=0 AND iParentId=:iParentId:";
        $param = array('iParentId' => $wid);
        $data = $this->modelsManager->createBuilder()
            ->columns("u.sStaffName,w.iWorkOrderId,w.iParentId,w.sWorkOrderName,w.dWorkTime,w.sWorkOrderContent,
            w.iLevel,w.iWorkOrderStatus,w.iProcess,w.sRemarks,w.sExplain,w.sComments,w.bIfChecked,w.tFromAt,w.tEndAt,
            w.tStartedAt,w.tFinishedAt,w.tCreateDate,w.tLastModifyDate,w.sEnclosure")
            ->addFrom('Admin\Models\pm\XhwoWorkOrder', 'w')
            ->leftjoin('Admin\Models\pm\XhwoWorkOrderMember', 'm.iWorkOrderId=w.iWorkOrderId AND m.bIfExecutor =1 AND m.bDelete = 0', 'm')
            ->leftjoin('Admin\Models\hrm\XhhrmStaff', 'm.iUserId = u.iUserId', 'u')
            ->where($condition, $param)
            ->inWhere('w.iWorkOrderId', $wids)
            ->getQuery()
            ->execute()
            ->toArray();
        foreach ($data as $k => $v) {
            $objs = $this->modelsManager->createBuilder()
                ->columns('iWorkOrderId')
                ->addFrom('Admin\Models\pm\XhwoWorkOrder')
                ->where($condition1, ['iParentId' => $v['iWorkOrderId']])
                ->inWhere('iWorkOrderId', $wids)
                ->getQuery()
                ->execute()
                ->toArray();

            if (!empty($objs)) {
                $data[$k]['state'] = "closed";
                $data[$k]['iconCls'] = 'fa fa-folder';
                $data[$k]['children'] = $this->getWorkOrderChildren($v['iWorkOrderId']);
            } else {
                $data[$k]['iconCls'] = 'fa fa-file-text';
            }
        }
        return $data;
    }

    /**
     * 新建workorder表单
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180418
     */
    public function workOrderFormAction()
    {
        $iWorkOrderId = $this->request->getQuery('iWorkOrderId', 'int');
        $ifNew = $this->request->getQuery('ifNew', 'int');
        if ($iWorkOrderId) {
            if (!Power::exist('Pm_Work_Order_Edit')) {
                return $this->sendViewError('无编辑工单权限');
            }
        } else {
            if (!Power::exist('Pm_Work_Order_Add')) {
                return $this->sendViewError('无新增工单权限');
            }
        }
        Assets::easyUI();
        Assets::datetimePicker();
        Assets::select2();
        Assets::viewer();
        $this->di->get('assets')
            ->addCss('assets/fileinput/fileinput.css')
            ->addJs('customer/js/fileinput.min.js')//修改过的
            ->addJs('customer/js/zh.js');
        Assets::importMainJs('assets/xh/xhForm.js');
        Assets::importJs('js/myMain.js');
        Assets::importJs('js/workorder/workOrderForm.js');
        $this->view->setVars([
            'iWorkOrderId' => $iWorkOrderId,
            'ifNew' => $ifNew,
            'workOrder_levels' => self::$workorder_levels,
        ]);
        $this->view->pick('workorder/workOrderForm');
    }

    /**
     * 新建工单
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180528
     */
    public function newWorkOrderAction()
    {
        $userId = Main::getLoginUserInfo('userId');
        $userName = Main::getLoginUserInfo('userName');
        try {
            $this->db->begin();
            $memberIds = $this->request->getPost('memberIds') ? $this->request->getPost('memberIds') : [];
            $parentId = $this->request->getPost('iParentId', 'int', 0);//members 后续可能会加入后台先保留
            $memberIds = array_filter(array_unique(array_merge($memberIds, [$userId])));
            $executorIds = $this->request->getPost('executorIds') ? $this->request->getPost('executorIds') : [];
            $templateId = $this->request->getPost('iTemplateId', 'int', 0);
            $sEnclosure = $this->request->getPost('enclosureUrl') ? $this->request->getPost('enclosureUrl') : [];
            if ($parentId) {
                $parentWorkorder = XhwoWorkOrder::findFirst([
                    'columns' => 'iWorkOrderStatus',
                    'conditions' => 'bDelete = 0 and iWorkOrderId = ' . $parentId,
                ]);
                if (!$parentWorkorder) {
                    return $this->sendErrorResponse('400', '父级工单不存在');
                } else {
                    if (in_array($parentWorkorder->iWorkOrderStatus, [3, 4])) {
                        return $this->sendErrorResponse('400', '父级工单已完成/退回');
                    }
                }
            }
            if ($executorIds) {
                $smsDatas = [];
                if ($templateId) {
                    $templateObj = XHBpmTemplate::findFirst($templateId);
                    if (!$templateObj) {
                        return $this->sendErrorResponse('400', '工单模板不存在');
                    }
                    $nodes = XHBpmNode::find([
                        'conditions' => "bDelete = 0 AND iTPId = $templateId"
                    ])->toArray();
                    foreach ($executorIds as $k => $executorId) {
                        $workOrderObj = new XhwoWorkOrder();
                        $workOrderObj->iWorkOrderStatus = 1;
                        $workOrderObj->assign($this->request->getPost());
                        $workOrderObj->tFromAt = empty($this->request->getPost('tFromAt')) ? '0000-00-00 00:00:00' : $this->request->getPost('tFromAt');
                        $workOrderObj->tEndAt = empty($this->request->getPost('tEndAt')) ? '0000-00-00 00:00:00' : $this->request->getPost('tEndAt');
                        $workOrderObj->iParentId = 0;
                        $workOrderObj->sEnclosure = json_encode($sEnclosure);
                        $workOrderObj->bIfMultiple = 1;
                        $result = $workOrderObj->save();
                        if (!$result) {
                            $this->db->rollback();
                            return $this->sendErrorResponse(500, '创建工单失败');
                        }
                        $userInfo = XhsysUser::findFirst([
                            'columns' => "sSelfPhone",
                            'conditions' => "iUserId = $executorId ANd bDelete = 0"
                        ]);
                        if ($userInfo && $userInfo->sSelfPhone) {
                            $smsDatas[$k]['phoneNum'] = $userInfo->sSelfPhone;
                            $smsDatas[$k]['msg'] = '您收到一份新的工单({' . $workOrderObj->sWorkOrderName . '}),请及时查看。';
                        }
                        $woMemberIds = array_filter(array_unique(array_merge($memberIds, [$executorId])));
                        $woMemberIds = array_unique($woMemberIds);
                        foreach ($woMemberIds as $woMemberId) {
                            //父级start
                            //避免重复添加
                            $pMember = XhwoWorkOrderMember::findFirst([
                                'columns' => 'iId',
                                'conditions' => 'bDelete=0 AND iUserId=:iUserId: AND iWorkOrderId = :iWorkOrderId:',
                                'bind' => array('iUserId' => $woMemberId, 'iWorkOrderId' => $workOrderObj->iWorkOrderId),
                            ]);
                            if (!$pMember) {
                                $pMember = new XhwoWorkOrderMember();
                                $pMember->iWorkOrderId = $workOrderObj->iWorkOrderId;
                                $pMember->iUserId = $woMemberId;
                                if ($woMemberId == $userId) {
                                    $pMember->bIfCreator = 1;//是否是创建者
                                }
                                if ($woMemberId == $executorId) {
                                    $pMember->bIfExecutor = 1;//是否是执行者
                                }
                                $r = $pMember->save();
                                if (!$r) {
                                    $this->db->rollback();
                                    return $this->sendErrorResponse(500, '创建工单失败', '添加工单相关人员失败');
                                }
                            }
                            //父级end
                        }
                        foreach ($nodes as $node) {
                            $workorder = new XhwoWorkOrder();
                            $workorder->iWorkOrderStatus = 1;
                            $workorder->assign($this->request->getPost());
                            $workorder->tFromAt = empty($this->request->getPost('tFromAt')) ? '0000-00-00 00:00:00' : $this->request->getPost('tFromAt');
                            $workorder->tEndAt = empty($this->request->getPost('tEndAt')) ? '0000-00-00 00:00:00' : $this->request->getPost('tEndAt');
                            $workorder->iParentId = $workOrderObj->iWorkOrderId;
                            $workorder->sEnclosure = json_encode($sEnclosure);
                            $workorder->sWorkOrderName = $node['sNodeName'];
                            $workorder->sWorkOrderContent = $node['sContent'];
                            $workorder->sRemarks = $node['mDesc'];
                            $workorder->bIfMultiple = 0;
                            $result = $workorder->save();
                            if (!$result) {
                                return $this->sendErrorResponse('500', '模板节点创建工单失败');
                            }
                            foreach ($woMemberIds as $woMemberId) {
                                $member = XhwoWorkOrderMember::findFirst([
                                    'columns' => 'iId',
                                    'conditions' => 'bDelete=0 AND iUserId=:iUserId: AND iWorkOrderId = :iWorkOrderId:',
                                    'bind' => array('iUserId' => $woMemberId, 'iWorkOrderId' => $workorder->iWorkOrderId),
                                ]);
                                if ($member) {
                                    continue;
                                }
                                $woMember = new XhwoWorkOrderMember();
                                $woMember->iWorkOrderId = $workorder->iWorkOrderId;
                                $woMember->iUserId = $woMemberId;
                                if ($woMemberId == $userId) {
                                    $woMember->bIfCreator = 1;//是否是创建者
                                }
                                if ($woMemberId == $executorId) {
                                    $woMember->bIfExecutor = 1;//是否是执行者
                                }
                                $re = $woMember->save();
                                if (!$re) {
                                    $this->db->rollback();
                                    return $this->sendErrorResponse(500, '创建工单失败', '添加工单相关人员失败');
                                }
                            }
                        }
                        //写入工单日志
                        $sContent = $userName . '创建工单' . $workOrderObj->sWorkOrderName;
                        $log = new XhwoWorkOrderLog();
                        $log->iWorkOrderId = $workOrderObj->iWorkOrderId;
                        $log->sContent = $sContent;
                        $r = $log->save();
                        if (!$r) {
                            $this->db->rollback();
                            return $this->sendErrorResponse(500, '创建工单失败', '创建工单日志失败');
                        }
                    }
                } else {
                    if ($parentId == 0 && count($executorIds) > 1) {
                        $woObj = new XhwoWorkOrder();
                        $woObj->iWorkOrderStatus = 1;
                        $woObj->assign($this->request->getPost());
                        $woObj->tFromAt = empty($this->request->getPost('tFromAt')) ? '0000-00-00 00:00:00' : $this->request->getPost('tFromAt');
                        $woObj->tEndAt = empty($this->request->getPost('tEndAt')) ? '0000-00-00 00:00:00' : $this->request->getPost('tEndAt');
                        $woObj->sEnclosure = json_encode($sEnclosure);
                        $woObj->iParentId = 0;
                        $woObj->bIfMultiple = 1;//多个执行者,
                        $res = $woObj->save();
                        if (!$res) {
                            $this->db->rollback();
                            return $this->sendErrorResponse(500, '创建工单失败');
                        }
                        //父级start
                        $pMember = new XhwoWorkOrderMember();
                        $pMember->iWorkOrderId = $woObj->iWorkOrderId;
                        $pMember->iUserId = $userId;
                        $pMember->bIfCreator = 1;
                        $pMember->bIfExecutor = 1;
                        $r = $pMember->save();
                        if (!$r) {
                            $this->db->rollback();
                            return $this->sendErrorResponse(500, '创建工单失败', '添加工单相关人员失败');
                        }
                        //父级end
                        foreach ($executorIds as $k => $executorId) {
                            //避免重复添加
                            $paMember = XhwoWorkOrderMember::findFirst([
                                'columns' => 'iId',
                                'conditions' => 'bDelete=0 AND iUserId=:iUserId: AND iWorkOrderId = :iWorkOrderId: AND bIfCreator = 1',
                                'bind' => array('iUserId' => $executorId, 'iWorkOrderId' => $woObj->iWorkOrderId),
                            ]);
                            if (!$paMember) {
                                $parentMember = new XhwoWorkOrderMember();
                                $parentMember->iWorkOrderId = $woObj->iWorkOrderId;
                                $parentMember->iUserId = $executorId;
                                $rest = $parentMember->save();
                                if (!$rest) {
                                    $this->db->rollback();
                                    return $this->sendErrorResponse(500, '创建工单失败', '添加工单相关人员失败');
                                }
                            }
                            $workOrderObj = new XhwoWorkOrder();
                            $workOrderObj->iWorkOrderStatus = 1;
                            $workOrderObj->assign($this->request->getPost());
                            $workOrderObj->tFromAt = empty($this->request->getPost('tFromAt')) ? '0000-00-00 00:00:00' : $this->request->getPost('tFromAt');
                            $workOrderObj->tEndAt = empty($this->request->getPost('tEndAt')) ? '0000-00-00 00:00:00' : $this->request->getPost('tEndAt');
                            $workOrderObj->iParentId = $woObj->iWorkOrderId;
                            $workOrderObj->sEnclosure = json_encode($sEnclosure);
                            $workOrderObj->bIfMultiple = 0;
                            $result = $workOrderObj->save();
                            if (!$result) {
                                $this->db->rollback();
                                return $this->sendErrorResponse(500, '创建工单失败');
                            }
                            $userInfo = XhsysUser::findFirst([
                                'columns' => "sSelfPhone",
                                'conditions' => "iUserId = $executorId ANd bDelete = 0"
                            ]);
                            if ($userInfo && $userInfo->sSelfPhone) {
                                $smsDatas[$k]['phoneNum'] = $userInfo->sSelfPhone;
                                $smsDatas[$k]['msg'] = '您收到一份新的工单({' . $workOrderObj->sWorkOrderName . '}),请及时查看。';
                            }
                            $woMemberIds = array_filter(array_unique(array_merge($memberIds, [$executorId])));
                            $woMemberIds = array_unique($woMemberIds);
                            foreach ($woMemberIds as $woMemberId) {
                                //子级
                                $member = XhwoWorkOrderMember::findFirst([
                                    'columns' => 'iId',
                                    'conditions' => 'bDelete=0 AND iUserId=:iUserId: AND iWorkOrderId = :iWorkOrderId:',
                                    'bind' => array('iUserId' => $woMemberId, 'iWorkOrderId' => $workOrderObj->iWorkOrderId),
                                ]);
                                if ($member) {
                                    continue;
                                }
                                $woMember = new XhwoWorkOrderMember();
                                $woMember->iWorkOrderId = $workOrderObj->iWorkOrderId;
                                $woMember->iUserId = $woMemberId;
                                if ($woMemberId == $userId) {
                                    $woMember->bIfCreator = 1;//是否是创建者
                                }
                                if ($woMemberId == $executorId) {
                                    $woMember->bIfExecutor = 1;//是否是执行者
                                }
                                $re = $woMember->save();
                                if (!$re) {
                                    $this->db->rollback();
                                    return $this->sendErrorResponse(500, '创建工单失败', '添加工单相关人员失败');
                                }
                            }
                            //写入工单日志
                            $sContent = $userName . '创建工单' . $workOrderObj->sWorkOrderName;
                            $log = new XhwoWorkOrderLog();
                            $log->iWorkOrderId = $workOrderObj->iWorkOrderId;
                            $log->sContent = $sContent;
                            $r = $log->save();
                            if (!$r) {
                                $this->db->rollback();
                                return $this->sendErrorResponse(500, '创建工单失败', '创建工单日志失败');
                            }
                        }
                    } elseif (count($executorIds) == 1) {
                        foreach ($executorIds as $k => $executorId) {
                            $workOrderObj = new XhwoWorkOrder();
                            $workOrderObj->iWorkOrderStatus = 1;
                            $workOrderObj->assign($this->request->getPost());
                            $workOrderObj->tFromAt = empty($this->request->getPost('tFromAt')) ? '0000-00-00 00:00:00' : $this->request->getPost('tFromAt');
                            $workOrderObj->tEndAt = empty($this->request->getPost('tEndAt')) ? '0000-00-00 00:00:00' : $this->request->getPost('tEndAt');
                            $workOrderObj->bIfMultiple = 0;
                            $workOrderObj->sEnclosure = json_encode($sEnclosure);
                            $result = $workOrderObj->save();
                            if (!$result) {
                                $this->db->rollback();
                                return $this->sendErrorResponse(500, '创建工单失败');
                            }
                            $userInfo = XhsysUser::findFirst([
                                'columns' => "sSelfPhone",
                                'conditions' => "iUserId = $executorId ANd bDelete = 0"
                            ]);
                            if ($userInfo && $userInfo->sSelfPhone) {
                                $smsDatas[$k]['phoneNum'] = $userInfo->sSelfPhone;
                                $smsDatas[$k]['msg'] = '您收到一份新的工单({' . $workOrderObj->sWorkOrderName . '}),请及时查看。';
                            }
                            $woMemberIds = array_filter(array_unique(array_merge($memberIds, [$executorId])));
                            $woMemberIds = array_unique($woMemberIds);
                            foreach ($woMemberIds as $woMemberId) {
                                //避免重复添加
                                $member = XhwoWorkOrderMember::findFirst([
                                    'columns' => 'iId',
                                    'conditions' => 'bDelete=0 AND iUserId=:iUserId: AND iWorkOrderId = :iWorkOrderId:',
                                    'bind' => array('iUserId' => $woMemberId, 'iWorkOrderId' => $workOrderObj->iWorkOrderId),
                                ]);
                                if ($member) {
                                    continue;
                                }
                                $woMember = new XhwoWorkOrderMember();
                                $woMember->iWorkOrderId = $workOrderObj->iWorkOrderId;
                                $woMember->iUserId = $woMemberId;
                                if ($woMemberId == $userId) {
                                    $woMember->bIfCreator = 1;  //是否是创建者
                                }
                                if ($woMemberId == $executorId) {
                                    $woMember->bIfExecutor = 1;//是否是执行者
                                }
                                $re = $woMember->save();
                                if (!$re) {
                                    $this->db->rollback();
                                    return $this->sendErrorResponse(500, '创建工单失败', '添加工单相关人员失败');
                                }
                                if ($parentId > 0) {
                                    $pMemberIds = XhwoWorkOrderMember::find([
                                        'columns' => 'iUserId',
                                        'conditions' => "bDelete=0 AND iWorkOrderId = $parentId",
                                    ])->toArray();
                                    $pMemberIds = array_column($pMemberIds, iUserId);
                                    $newMemberIds = array_diff($woMemberIds, $pMemberIds);
                                    foreach ($newMemberIds as $newMemberId) {
                                        $parentMemObj = new XhwoWorkOrderMember();
                                        $parentMemObj->iUserId = $newMemberId;
                                        $parentMemObj->iTaskId = $parentId;
                                        $resu = $parentMemObj->save();
                                        if (!$resu) {
                                            $this->db->rollback();
                                            return $this->sendErrorResponse(500, '创建工单失败', '添加工单相关人员失败');
                                        }
                                    }
                                }
                            }
                            //写入工单日志
                            $sContent = $userName . '创建工单' . $workOrderObj->sWorkOrderName;
                            $log = new XhwoWorkOrderLog();
                            $log->iWorkOrderId = $workOrderObj->iWorkOrderId;
                            $log->sContent = $sContent;
                            $r = $log->save();
                            if (!$r) {
                                $this->db->rollback();
                                return $this->sendErrorResponse(500, '创建工单失败', '创建工单日志失败');
                            }
                        }
                        if ($parentId) {
                            $pre = $this->modifyParentWorkorder($parentId);
                            if (!$pre) {
                                $this->db->rollback();
                                return $this->sendErrorResponse(500, '新建工单失败', '父级工单修改进度失败');
                            }
                        }
                    }
                }
            } else {
                $this->db->rollback();
                return $this->sendErrorResponse(500, '创建工单失败', '请选择工单执行人');
            }
            $this->db->commit();
            $this->multiSendSms($smsDatas);
            return $this->sendSuccessResponse('创建工单成功');
        } catch (\Exception $exception) {
            $this->db->rollback();
            return $this->sendErrorResponse(500, $exception->getMessage());
        }
    }

    /**
     *编辑工单
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180418
     */
    public function editWorkOrderAction()
    {
        $iWorkOrderId = $this->request->getPost('iWorkOrderId', 'int');
        $sEnclosure = $this->request->getPost('enclosureUrl') ? $this->request->getPost('enclosureUrl') : [];
        //创建人id  && name
        $userId = Main::getLoginUserInfo('userId');
        $userName = Main::getLoginUserInfo('userName');
        try {
            $this->db->begin();  //开启事务
            if (!Power::exist('Pm_Work_Order_Edit')) {
                return $this->sendErrorResponse(400, '权限不足', '无编辑工单权限');
            }
            if (!$iWorkOrderId) {
                return $this->sendErrorResponse(400, '缺少参数');
            }
            $workOrder = XhwoWorkOrder::findFirst([
                'conditions' => "iWorkOrderId = $iWorkOrderId AND bDelete = 0"
            ]);
            if (!$workOrder) {
                return $this->sendErrorResponse(500, '编辑工单失败', '工单信息不存在');
            }
            if ($workOrder->bIfMultiple == 1 && empty($workOrder->iTemplateId)) {
                $creator = XhwoWorkOrderMember::findFirst([
                    'conditions' => "iUserId = $userId AND (bIfCreator = 1)  AND iWorkOrderId = $iWorkOrderId",
                ]);
                if (!User::isAdmin() && !$creator) {
                    return $this->sendErrorResponse(500, '编辑工单失败', '该工单只能由创建者编辑');
                }
            } else {
                $creator = XhwoWorkOrderMember::findFirst([
                    'conditions' => "iUserId = $userId AND (bIfCreator = 1 or bIfExecutor = 1)  AND iWorkOrderId = $iWorkOrderId",
                ]);
                if (!User::isAdmin() && !$creator) {
                    return $this->sendErrorResponse(500, '编辑工单失败', '非工单创建或执行者');
                }
            }
            if ($workOrder->iWorkOrderStatus == 3 || $workOrder->iWorkOrderStatus == 4) {
                return $this->sendErrorResponse(500, '编辑工单失败', '工单已完成或已退回');
            }
            $smsDatas = [];
            $newData = $this->request->getPost();
            $oldData = $workOrder->toArray();
            $diff = array_diff($newData, $oldData);
            //获取原执行人
            $oldExecutors = $this->modelsManager->createBuilder()
                ->columns("u.sStaffName,m.iUserId")
                ->addFrom('Admin\Models\pm\XhwoWorkOrderMember', 'm')
                ->leftjoin('Admin\Models\hrm\XhhrmStaff', 'm.iUserId = u.iUserId', 'u')
                ->where("m.bDelete = 0 AND m.bIfExecutor = 1 AND m.iWorkOrderId = $iWorkOrderId")
                ->getQuery()
                ->execute()
                ->toArray();
            $newExecutors = $this->request->getPost('executorIds') ? $this->request->getPost('executorIds') : [];
            $memberIds = $this->request->getPost('memberIds') ? $this->request->getPost('memberIds') : [];//后续可能会添加工单成员
            //写入工单日志(根据更新的数据)
            $sContent = $userName . '编辑工单' . $workOrder->sWorkOrderName;
            $levels = self::$workorder_levels;
            foreach ($diff as $k => $v) {
                switch ($k) {
                    case 'sWorkOrderName':
                        $sContent .= $oldData['sWorkOrderName'] ? ',将工单名称由 ' . $oldData['sWorkOrderName'] . ',修改为 ' . $v : ' 将工单名称修改为 ' . $v;
                        break;
                    case 'sWorkOrderContent':
                        $sContent .= $oldData['sWorkOrderContent'] ? ',将工单内容由 ' . $oldData['sWorkOrderContent'] . ',修改为 ' . $v : '将工单内容修改为 ' . $v;
                        break;
                    case 'sRemarks':
                        $sContent .= $oldData['sRemarks'] ? ',将工单备注由 ' . $oldData['sRemarks'] . ',修改为' . $v : '将工单备注修改为 ' . $v;
                        break;
                    case 'iProcess':
                        $sContent .= $oldData['iProcess'] ? ',将工单完成进度由 ' . $oldData['iProcess'] . '%,修改为 ' . $v : '将工单完成进度修改为 ' . $v . '%';
                        break;
                    case 'tFromAt':
                        $sContent .= $oldData['tFromAt'] ? ',将工单预计开始时间由 ' . $oldData['tFromAt'] . ',修改为 ' . $v : '将工单预计开始时间修改为 ' . $v;
                        break;
                    case 'tEndAt':
                        $sContent .= $oldData['tEndAt'] ? ',将工单预计结束时间由 ' . $oldData['tEndAt'] . ',修改为 ' . $v : '将工单预计结束时间修改为 ' . $v;
                        break;
                    case 'dWorkTime':
                        $sContent .= $oldData['dWorkTime'] ? ',将工单工时由 ' . $oldData['dWorkTime'] . ',修改为 ' . $v : '将工单工时修改为 ' . $v;
                        break;
                    case 'iLevel':
                        $sContent .= $oldData['iLevel'] ? ',将工单等级由 ' . $levels[$oldData['iLevel']] . ',修改为 ' . $levels[$v] : '将工单等级修改为 ' . $levels[$v];
                        break;
                    case 'executorIds':
                        if ($oldExecutors[0]['iUserId'] != $v[0]) {
                            if ($v[0] || $oldExecutors[0]['iUserId']) {
                                $newUser = XhsysUser::findFirst([
                                    'conditions' => "iUserId = $v[0] AND bDelete = 0",
                                ]);
                                if ($oldExecutors[0]['iUserId'] && $newUser) {
                                    $sContent .= ',将工单执行人由 ' . $oldExecutors[0]['sUserName'] . '修改为 ' . $newUser->sUserName;
                                }
                            }
                        }
                        break;
                }
            }
            $workOrder->assign($this->request->getPost());
            $workOrder->tFromAt = empty($this->request->getPost('tFromAt')) ? '0000-00-00 00:00:00' : $this->request->getPost('tFromAt');
            $workOrder->tEndAt = empty($this->request->getPost('tEndAt')) ? '0000-00-00 00:00:00' : $this->request->getPost('tEndAt');
            $workOrder->sEnclosure = json_encode($sEnclosure);
            $result = $workOrder->save();
            if (!$result) {
                $this->db->rollback();
                return $this->sendErrorResponse(500, '编辑工单失败');
            }
            if (!empty($newExecutors) && $newExecutors[0] != $oldExecutors[0]['iUserId']) {
                $userInfo = XhsysUser::findFirst([
                    'columns' => "sSelfPhone",
                    'conditions' => "iUserId = $newExecutors[0] ANd bDelete = 0"
                ]);
                if ($userInfo && $userInfo->sSelfPhone) {
                    $smsDatas[0]['phoneNum'] = $userInfo->sSelfPhone;
                    $smsDatas[0]['msg'] = '您收到一份新的工单({' . $workOrder->sWorkOrderName . '}),请及时查看。';
                }
            }
            $log = new XhwoWorkOrderLog();
            $log->iWorkOrderId = $workOrder->iWorkOrderId;
            $log->sContent = $sContent;
            $r = $log->save();
            if (!$r) {
                $this->db->rollback();
                return $this->sendErrorResponse(500, '编辑工单失败', '创建工单日志失败');
            }
            //成员表添加
            //先把之前的用户删除
            $members = XhwoWorkOrderMember::find([
                'conditions' => 'bDelete=0 AND iWorkOrderId = :iWorkOrderId:',
                'bind' => array('iWorkOrderId' => $iWorkOrderId),
            ]);
            foreach ($members as $member) {
                if ($member->bIfCreator == 1) {
                    if (in_array($member->iUserId, $newExecutors)) {
                        $member->bIfExecutor = 1;
                    } else {
                        $member->bIfExecutor = 0;
                    }
                } else {
                    $member->bDelete = 1;
                }
                $res = $member->save();
                if (!$res) {
                    $this->db->rollback();
                    return $this->sendErrorResponse(500, '编辑工单失败', '工单相关人员编辑失败');
                }
            }
            $woMemberIds = array_filter(array_unique(array_merge($memberIds, $newExecutors)));
            $woMemberIds = array_unique($woMemberIds);
            foreach ($woMemberIds as $woMemberId) {
                //避免重复添加
                $member = XhwoWorkOrderMember::findFirst([
                    'columns' => 'iId',
                    'conditions' => 'bDelete=0 AND iUserId=:iUserId: AND iWorkOrderId = :iWorkOrderId:',
                    'bind' => array('iUserId' => $woMemberId, 'iWorkOrderId' => $workOrder->iWorkOrderId),
                ]);
                if ($member) {
                    continue;
                }
                $woMember = new XhwoWorkOrderMember();
                $woMember->iWorkOrderId = $workOrder->iWorkOrderId;
                $woMember->iUserId = $woMemberId;
                if ($woMemberId == $newExecutors[0]) {
                    $woMember->bIfExecutor = 1;//是否是执行者
                }
                $re = $woMember->save();
                if (!$re) {
                    $this->db->rollback();
                    return $this->sendErrorResponse(500, '编辑工单失败', '工单相关人员编辑失败');
                }
            }
            $this->db->commit();
            $this->multiSendSms($smsDatas);
            return $this->sendSuccessResponse('编辑工单成功');
        } catch (\Exception $exception) {
            $this->db->rollback();
            return $this->sendErrorResponse(500, $exception->getMessage());
        }
    }

    /**
     * 审核
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180525
     */
    public function checkWorkOrderAction()
    {
        $iWorkOrderId = $this->request->getPost('iWorkOrderId', 'int');
        //创建人id  && name
        $userId = Main::getLoginUserInfo('userId');
        $userName = Main::getLoginUserInfo('userName');
        $date = date('Y-m-d H:i:s', time());
        $sComments = $this->request->getPost('sComments', 'string');
        $comment = [
            'uname' => $userName,
            'date' => $date,
            'sComments' => $sComments
        ];
        $comment = json_encode($comment);
        try {
            $this->db->begin();  //开启事务
            if (!Power::exist('Pm_Work_Order_Check')) {
                return $this->sendErrorResponse(400, '权限不足', '无审核工单权限');
            }
            if (!$iWorkOrderId) {
                return $this->sendErrorResponse(400, '缺少参数');
            }
            $workOrder = XhwoWorkOrder::findFirst([
                'conditions' => "iWorkOrderId = $iWorkOrderId AND bDelete = 0"
            ]);
            $creator = XhwoWorkOrderMember::findFirst([
                'conditions' => "iUserId = $userId AND bIfCreator = 1  AND iWorkOrderId = $iWorkOrderId",
            ]);
            if (!$workOrder || (!User::isAdmin() && !$creator)) {
                return $this->sendErrorResponse(400, '审核工单失败', '非工单创建人无法审核工单');
            }
            if ($workOrder->iWorkOrderStatus != 3 && $workOrder->iWorkOrderStatus != 4) {
                return $this->sendErrorResponse(500, '审核工单失败', '工单在完成或者退回状态下才能审核');
            }
            $workOrder->bIfChecked = 1;
            $workOrder->sComments = $comment;
            $result = $workOrder->save();
            if (!$result) {
                $this->db->rollback();
                return $this->sendErrorResponse(500, '审核工单失败');
            }
            //写入工单日志
            $sContent = $userName . '审核工单' . $workOrder->sWorkOrderName;
            $log = new XhwoWorkOrderLog();
            $log->iWorkOrderId = $workOrder->iWorkOrderId;
            $log->sContent = $sContent;
            $r = $log->save();
            if (!$r) {
                $this->db->rollback();
                return $this->sendErrorResponse(500, '审核工单失败', '审核工单创建日志失败');
            }
            $this->db->commit();
            return $this->sendSuccessResponse('审核工单成功');
        } catch (\Exception $exception) {
            $this->db->rollback();
            return $this->sendErrorResponse(500, $exception->getMessage());
        }
    }

    /**
     * 获取工单信息
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180408
     */
    public function getWorkOrderInfoAction()
    {
        try {
            $iWorkOrderId = $this->request->getPost('iWorkOrderId', 'int');
            if (!$iWorkOrderId) {
                return $this->sendErrorResponse(400, '缺少参数');
            };
            $workOrderInfo = XhwoWorkOrder::findFirst([
                'conditions' => 'bDelete=0 AND iWorkOrderId = :iWorkOrderId:',
                'bind' => array('iWorkOrderId' => $iWorkOrderId),
            ]);
            $executorIds = $this->modelsManager->createBuilder()
                ->columns("m.iUserId,u.sStaffName")
                ->addFrom('Admin\Models\pm\XhwoWorkOrderMember', 'm')
                ->leftjoin('Admin\Models\hrm\XhhrmStaff', 'm.iUserId = u.iUserId', 'u')
                ->where('m.bDelete = 0 AND m.bIfExecutor = 1 AND m.iWorkOrderId = :iWorkOrderId:', array('iWorkOrderId' => $iWorkOrderId))
                ->getQuery()
                ->execute()
                ->toArray();
            $memembers = XhwoWorkOrderMember::find([
                'columns' => 'iUserId',
                'conditions' => 'bDelete=0 AND iWorkOrderId = :iWorkOrderId: ',
                'bind' => array('iWorkOrderId' => $iWorkOrderId),
            ])->toArray();
            $memberIds = [];
            foreach ($memembers as $memember) {
                $memberIds[] = $memember['iUserId'];
            }
            $exeIds = [];
            foreach ($executorIds as $executorId) {
                $exeIds[] = $executorId['iUserId'];
            }
            $info = $workOrderInfo ? $workOrderInfo->toArray() : [];
            $info['executorIds'] = $exeIds;
            $info['memberIds'] = $memberIds;
            $info['sEnclosure'] = json_decode($info['sEnclosure'], true);
            return $this->sendJsonResponse($info);
        } catch (\Exception $exception) {
            return $this->sendErrorResponse(500, $exception->getMessage());
        }
    }

    /**
     * 开始或者完成
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180420
     * modify by zqk 20180510
     */
    public function alterStatusAction()
    {
        if (!Power::exist('Pm_Work_Order_AlterStatus')) {
            return $this->sendErrorResponse(400, '权限不足', '无变更工单状态权限');
        }
        $userId = Main::getLoginUserInfo('userId');
        $iWorkOrderId = $this->request->getPost('iWorkOrderId', 'int');
        $status = $this->request->getPost('iWorkOrderStatus', 'int');
        try {
            $this->db->begin(); //开启事务
            $workOrder = XhwoWorkOrder::findFirst([
                'conditions' => "iWorkOrderId = $iWorkOrderId AND bDelete = 0"
            ]);
            $parentId = $workOrder->iParentId;
            if ($parentId) {
                $parentWorkorder = XhwoWorkOrder::findFirst([
                    'columns' => 'iWorkOrderStatus',
                    'conditions' => 'bDelete = 0 AND iWorkOrderId = ' . $parentId,
                ]);
                if (!$parentWorkorder) {
                    return $this->sendErrorResponse('400', '父级工单不存在');
                } else {
                    if (in_array($parentWorkorder->iWorkOrderStatus, [3, 4])) {
                        return $this->sendErrorResponse('400', '父级工单已完成/退回');
                    }
                }
            }
            $creator = XhwoWorkOrderMember::findFirst([
                'conditions' => "iUserId = $userId AND  bIfExecutor = 1 AND iWorkOrderId = $iWorkOrderId",
            ]);
            if (!$iWorkOrderId || !in_array($status, [2, 3, 4])) {
                return $this->sendErrorResponse(400, '参数错误');
            }
            if (!$workOrder || (!User::isAdmin() && !$creator)) {
                return $this->sendErrorResponse(500, '操作失败', '非工单执行者');
            }
            if ($workOrder->iWorkOrderStatus == $status) {
                return $this->sendErrorResponse(500, '操作失败', '工单' . self::$workorder_status[$status]);
            }
            if ($workOrder->bIfChecked == 1) {
                return $this->sendErrorResponse(500, '工单状态错误', '工单已审核,无法更改状态');
            }
            //完成时子工单状态验证
            $condition = "bDelete=0 AND iParentId = :iParentId: AND (iWorkOrderStatus != 3  AND iWorkOrderStatus != 4 )";
            $parameter = array(
                'columns' => 'iWorkOrderId',
                'conditions' => $condition,
                'bind' => array('iParentId' => $iWorkOrderId),
            );
            $unfNum = XhwoWorkOrder::count($parameter);
            if ($unfNum && $status == 3) {
                return $this->sendErrorResponse(500, '子工单状态错误', '有未完成子工单,无法更改状态');
            }
            $date = date('Y-m-d H:i:s', time());
            if ($status == 3) {
                $workOrder->iProcess = 100;
                $workOrder->tFinishedAt = $date;
                $workOrder->sExplain = '';
            } elseif ($status == 2) {
                $workOrder->tStartedAt = $date;
                $workOrder->tFinishedAt = '0000-00-00 00:00:00';
                $workOrder->iProcess = 0;
                $workOrder->sExplain = '';
            } elseif ($status == 4) {
                $workOrder->sExplain = $this->request->getPost('sExplain', 'string');
            }
            $workOrder->iWorkOrderStatus = $status;
            $re = $workOrder->save();
            if (!$re) {
                $this->db->rollback();
                return $this->sendErrorResponse(500, '操作失败');
            }
            //父级工单进度修改
            if ($parentId) {
                $pre = $this->modifyParentWorkorder($parentId);
                if (!$pre) {
                    $this->db->rollback();
                    return $this->sendErrorResponse(500, '新建工单失败', '父级工单修改进度失败');
                }
            }
            $userName = Main::getLoginUserInfo('userName');
            $content = '';
            switch ($status) {
                case 2:
                    $content = $userName . '开启工单' . $workOrder->sWorkOrderName;
                    break;
                case 3:
                    $content = $userName . '完成工单' . $workOrder->sWorkOrderName;
                    break;
                case 4:
                    $content = $userName . '退回工单' . $workOrder->sWorkOrderName;
                    break;
            }
            $log = new XhwoWorkOrderLog();
            $log->iWorkOrderId = $workOrder->iWorkOrderId;
            $log->sContent = $content;
            $r = $log->save();
            if (!$r) {
                $this->db->rollback();
                return $this->sendErrorResponse(400, '操作失败', '工单操作日志创建失败');
            }
            $this->db->commit();
            return $this->sendSuccessResponse('操作成功');
        } catch (\Exception $e) {
            $this->db->rollback();
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 获取工单树结构信息  id ,text easyui
     * @return string
     * created by zqk 2018/4/16
     */
    public function getWorkOrdersAction()
    {
        $newArray[0]['id'] = 0;
        $newArray[0]['text'] = '父级工单';
        $newArray[0]['iconCls'] = 'fa fa-group';
        $newArray[0]['children'] = $this->getChildrenWorkOrder(0);
        return $this->sendJsonResponse($newArray);
    }

    /**
     * 获取子项目结构
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180409
     */
    private function getChildrenWorkOrder($iParentid)
    {
        $parameters = array(
            'conditions' => "bDelete=:bDelete: AND iParentId=:iParentId: ",
            'bind' => array('iParentId' => $iParentid, 'bDelete' => 0),
        );
        $objs = XhwoWorkOrder::find($parameters);
        if ($objs == null) {
            return [];
        }
        $array = $objs->toArray();
        $newArray = [];
        foreach ($array as $key => $value) {
            $newArray[$key]['id'] = $value['iWorkOrderId'];
            $newArray[$key]['text'] = $value['sWorkOrderName'];
            $newArray[$key]['iconCls'] = 'fa fa-group';
            $newArray[$key]['children'] = $this->getChildrenWorkOrder($value['iWorkOrderId']);
            if ($newArray[$key]['children']) {
                $newArray[$key]['state'] = "closed";
            }
        }
        return $newArray;
    }

    /**
     * 获取工单执行人列表
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180515
     */
    public function getUserIdsAction()
    {
        $conditions = 's.bDelete = 0 and u.bDelete = 0 AND s.iStaffStatus = 1 ';
        $staffs = $this->modelsManager->createBuilder()
            ->columns("s.iUserId,s.sStaffName,s.sPostName")
            ->addFrom('Admin\Models\hrm\XhhrmStaff', 's')
            ->leftjoin('Admin\Models\user\XhsysUser', 's.iUserId = u.iUserId', 'u')
            ->where($conditions)
            ->getQuery()
            ->execute()
            ->toArray();
        return $this->sendJsonResponse($staffs);
    }

    /**
     * 获取工单模板列表
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180706
     */
    public function getTemplateIdsAction()
    {
        if (User::isAdmin()) {
            $condition = 'bDelete = 0 AND iType > 0';
        } else {
            $userId = Main::getLoginUserInfo('userId');
            $depIds = Main::getLoginUserInfo('depId');
            $deps = implode(",%' OR  sDepIds like '%,", $depIds);
            $condition = 'bDelete = 0';
            $condition .= " AND ((sDepIds like '%," . $deps . ",%' AND iType=3) OR (iType=1)  OR (iType=2 AND iCreateUserId= $userId) ) ";//部门 通用 个人
        }
        $templates = $this->modelsManager->createBuilder()
            ->columns("iTPId as iId,sTPName as sName")
            ->addFrom('Admin\Models\bpm\XHBpmTemplate')
            ->where($condition)
            ->getQuery()
            ->execute()
            ->toArray();
        return $this->sendJsonResponse($templates);
    }

    /**
     * 获取工单成员Ids(参与人)
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180509
     */
    public function getMemberIdsAction()
    {
        $iWorkOrderId = $this->request->getPost('iWorkOrderId', 'int');//项目id
        $inmembers = $this->request->getPost('memberIds');//项目成员条件
        //获取已选成员 新建版本默认已选项目成员   编辑默认已选本编辑项目成员
        if (!isset($inmembers)) {
            if ($iWorkOrderId) {//编辑成员
                $parameters = array(
                    'columns' => 'iUserId',
                    'conditions' => "bDelete=:bDelete: AND iWorkOrderId=:iWorkOrderId: AND bIfExecutor = 0",
                    'bind' => array('iWorkOrderId' => $iWorkOrderId, 'bDelete' => 0),
                );
                $memberObj = new XhwoWorkOrderMember();
                $members = $memberObj->find($parameters)->toArray();
                foreach ($members as $k => $member) {
                    $inmembers[] = $member['iUserId'];
                }
            }
        }
        if ($inmembers) {
            $unames = $this->modelsManager->createBuilder()
                ->columns("u.sStaffName")
                ->addFrom('Admin\Models\hrm\XhhrmStaff', 's')
                ->leftjoin('Admin\Models\user\XhsysUser', 's.iUserId = u.iUserId', 'u')
                ->inWhere("s.iUserId", $inmembers)
                ->getQuery()
                ->execute()
                ->toArray();
            $memNames = '';
            $count = count($unames);
            foreach ($unames as $k => $uname) {
                if ($count == $k + 1) {
                    $memNames .= $uname['sStaffName'];
                } else {
                    $memNames .= $uname['sStaffName'] . ',';
                }
            }
            return $this->sendJsonResponse([$inmembers, $memNames]);
        } else {
            return $this->sendJsonResponse([]);
        }
    }

    /**
     * 获取可查看的工单ids
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180515
     */
    private function getWorkOrderIds()
    {
        $deps = User::getextrapower('dep', 'workorder');  //获取扩展部门权限
        $uids = [];
        if ($deps) {
            $deps = implode(",%' OR  sDepIds like '%,", $deps);
            $conditions = 'bDelete = 0';
            $conditions .= " AND (sDepIds like '%," . $deps . ",%' ) ";
            $users = $this->modelsManager->createBuilder()
                ->columns("iUserId")
                ->From('Admin\Models\hrm\XhhrmStaff')
                ->where($conditions)
                ->getQuery()
                ->execute()
                ->toArray();
            foreach ($users as $k => $user) {
                $uids[] = $user['iUserId'];
            }
        }
        $userId = Main::getLoginUserInfo('userId');
        array_push($uids, $userId);
        $uids = array_unique($uids);
        $iWorkOrderIds = $this->modelsManager->createBuilder()
            ->columns("iWorkOrderId")
            ->addFrom('Admin\Models\pm\XhwoWorkOrderMember')
            ->where('bDelete = 0')
            ->inwhere('iUserId', $uids)
            ->groupBy('iWorkOrderId')
            ->getQuery()
            ->execute()
            ->toArray();
        $wids = [];
        foreach ($iWorkOrderIds as $iWorkOrderId) {
            $wids[] = $iWorkOrderId['iWorkOrderId'];
        }
        return $wids;
    }

    /**
     * 删除工单
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180504
     */
    public function delWorkOrderByIdAction()
    {
        if (!Power::exist('Pm_Work_Order_Del')) {
            return $this->sendErrorResponse(500, '权限不足', '无删除工单权限');
        }
        $userName = Main::getLoginUserInfo('userName');
        $userId = Main::getLoginUserInfo('userId');
        $iWorkOrderId = $this->request->getPost('iWorkOrderId', 'int');
        try {
            $this->db->begin();
            $WorkOrderObj = XhwoWorkOrder::findFirst([
                'conditions' => "bDelete = 0 AND iWorkOrderId = $iWorkOrderId"
            ]);
            if (!$WorkOrderObj) {
                return $this->sendErrorResponse(400, '参数错误', '工单信息不存在');
            }
            $parentId = $WorkOrderObj->iParentId;
            if ($parentId) {
                $parentWorkorder = XhwoWorkOrder::findFirst([
                    'columns' => 'iWorkOrderStatus',
                    'conditions' => 'bDelete = 0 and iWorkOrderId = ' . $parentId,
                ]);
                if (!$parentWorkorder) {
                    return $this->sendErrorResponse('400', '父级工单不存在');
                } else {
                    if (in_array($parentWorkorder->iWorkOrderStatus, [3, 4])) {
                        return $this->sendErrorResponse('400', '父级工单已完成/退回');
                    }
                }
            }
            $creator = XhwoWorkOrderMember::findFirst([
                'conditions' => "iUserId = $userId AND bIfCreator = 1  AND iWorkOrderId = $iWorkOrderId",
            ]);
            if (!User::isAdmin() && !$creator) {
                return $this->sendErrorResponse(500, '删除失败', '只有工单创建者才能删除工单');
            }
            $WorkOrderObj->bDelete = 1;
            $re = $WorkOrderObj->save();
            if (!$re) {
                $this->db->rollback();
                return $this->sendErrorResponse('500', '删除失败');
            }
            //删除子工单
            $result = $this->delChildrenWorkOrders($iWorkOrderId);
            if (!$result) {
                $this->db->rollback();
                return $this->sendErrorResponse('500', '删除失败', '删除子工单失败');
            }
            $content = $userName . '删除工单' . $WorkOrderObj->sWorkOrderName;
            $Log = new XhwoWorkOrderLog();
            $Log->sContent = $content;
            $Log->iWorkOrderId = $iWorkOrderId;
            $res = $Log->save();
            if (!$res) {
                $this->db->rollback();
                return $this->sendErrorResponse('500', '删除失败', '创建日志失败');
            }
            //父级工单进度修改
            if ($parentId) {
                $pre = $this->modifyParentWorkorder($parentId);
                if (!$pre) {
                    $this->db->rollback();
                    return $this->sendErrorResponse(500, '删除工单失败', '父级工单修改进度失败');
                }
            }
            $this->db->commit();
            return $this->sendSuccessResponse('删除成功');
        } catch (\Exception $exception) {
            $this->db->rollback();
            return $this->sendErrorResponse(500, '操作失败', $exception->getMessage());
        }
    }

    /**
     * 删除子工单
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180504
     */
    private function delChildrenWorkOrders($id)
    {
        $workorders = XhwoWorkOrder::find([
            'conditions' => "bDelete = 0 AND iParentId = $id"
        ]);
        foreach ($workorders as $workorder) {
            $workorder->bDelete = 1;
            $re = $workorder->save();
            if (!$re) {
                return false;
            }
            $res = $this->delChildrenWorkOrders($workorder->iWorkOrderId);
            if (!$res) {
                return false;
            }
        }
        return true;
    }

    /**
     * 创建/编辑工单 批量发送短信
     *
     * create by zqk 20180711
     */
    private function multiSendSms($datas)
    {
        foreach ($datas as $data) {
            Main::sendSMS($data['phoneNum'], $data['msg']);
        }
    }

    /**
     * 修改父级工单
     *
     * @param $parentId
     *
     * @return bool
     *
     * create by zqk 20180919
     */
    private function modifyParentWorkorder($parentId)
    {
        $finCondition = "bDelete=0 AND iParentId = :iParentId: AND iWorkOrderStatus = 3";
        $finParameter = array(
            'columns' => 'iWorkOrderId',
            'conditions' => $finCondition,
            'bind' => array('iParentId' => $parentId),
        );
        $finNum = XhwoWorkOrder::count($finParameter);
        $sumCondition = "bDelete = 0 AND iWorkOrderStatus != 4 AND iParentId = :iParentId:";
        $sumParameter = array(
            'columns' => 'iWorkOrderId',
            'conditions' => $sumCondition,
            'bind' => array('iParentId' => $parentId),
        );
        $sumfNum = XhwoWorkOrder::count($sumParameter);
        if ($sumfNum) {
            $floatNum = intval($finNum) / $sumfNum;
            $process = intval(sprintf("%.2f", $floatNum) * 100);
            $fatherWo = XhwoWorkOrder::findFirst([
                'conditions' => "bDelete = 0 AND iWorkOrderId = $parentId"
            ]);
            $fatherWo->iProcess = $process;
            $fare = $fatherWo->save();
            if (!$fare) {
                return false;
            }
        }
        return true;
    }

    /**
     * 上传工单附件
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20180919
     */
    public function uploadFileAction()
    {
        if (!$this->request->hasFiles()) {
            return $this->sendErrorResponse(400, '缺少文件');
        }
        $file = $this->request->getUploadedFiles()[0];
        if (!in_array(strtolower($file->getExtension()), [
            'jpg', 'jpeg', 'png', 'bpm', 'gif', 'xlsx', 'docx', 'doc', 'pdf', 'xls', 'rar', 'zip', 'txt'])) {
            return $this->sendErrorResponse(500, '文件类型不正确');
        }
        $filePath = Tool::buildPath(Main::getConfigByName('fileSave')['temp'], $file->getName());
        $fileName = $file->getName();
        $file->moveTo($filePath);
        $url = Main::uploadToFileManageSystem($filePath, 'other', null, true);
        if (!$url) {
            return $this->sendErrorResponse(500, '文件上传失败:没有文件url');
        } else {
            return $this->sendSuccessResponse(['url' => $url, 'fileName' => $fileName]);
        }
    }

    public function delFileAction()
    {
        return $this->sendSuccessResponse('success');
    }

    /**
     * 附件展示页
     *
     * @return \Phalcon\Mvc\View|string
     *
     * create by zqk 20180920
     */
    public function showFileTableAction()
    {
        $id = $this->request->getQuery('iWorkOrderId');
        if (!$id) {
            return $this->sendViewError('缺少参数');
        }
        $workOrderInfo = XhwoWorkOrder::findFirst([
            'columns' => 'sEnclosure',
            'conditions' => 'bDelete=0 AND iWorkOrderId = :iWorkOrderId:',
            'bind' => array('iWorkOrderId' => $id),
        ]);
        if (!$workOrderInfo) {
            return $this->sendViewError('暂无数据');
        }
        if (!$workOrderInfo->sEnclosure) {
            $fileInfo = '0';
        } else {
            $fileInfoArr = json_decode($workOrderInfo->sEnclosure, true);
            $images = $files = [];
            foreach ($fileInfoArr as $value) {
                if ($value) {
                    $num = strrpos($value, '.');
                    if (in_array(substr($value, $num + 1), ['jpg', 'jpeg', 'png', 'bpm', 'gif'])) {
                        $images[] = $value;
                    } else {
                        $files[] = $value;
                    }
                }
            }
            $fileInfo['sImages'] = implode(',', $images);
            $fileInfo['sFiles'] = implode(',', $files);
        }
        $this->view->pick('workorder/showFileForm');
        Assets::viewer();
        Assets::easyUI('../customer/js/myMain.js');
        Assets::importJs('js/workorder/showFileForm.js');
        return $this->view->setVars([
            'info' => json_encode($fileInfo)
        ]);
    }
}

